package cn.itcast.dao.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    //一丶查询所有用户信息
    public List<User> findAll() {

        List<User> lis = new ArrayList<User>();

        try {
              /*
                   //1.注册驱动
                   Class.forName("com.mysql.jdbc.Driver");
                  //2.获取连接
                  conn = DriverManager.getConnection("jdbc:mysql://192.168.247.123/jdbc", "root", "root");

            */

            //工具类注册驱动获取连接
            conn = JDBCUtil.getConn();

            //3.编写sql
            String sql = "select * from user";
            //4.创建preparestatement 预编译对象
            ps = conn.prepareStatement(sql);
            //5.执行sql
            rs = ps.executeQuery();

            //6.遍历结果集
            while (rs.next()) {
                User user = new User(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4), rs.getFloat(5));
                lis.add(user);

            }

            //7.释放资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }


        return lis;
    }

    //二丶添加用户
    public void add(User user) {
        try {
            //1.获取连接
            conn = JDBCUtil.getConn();
            //2.编写sql,并创建预编译对象
            String sql = "insert into user values(?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            //2.1添加数据,并执行
            ps.setInt(1,user.getId());
            ps.setString(2,user.getName());
            ps.setInt(3,user.getAge());
            ps.setString(4,user.getSex());
            ps.setFloat(5,user.getMoney());
            ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            JDBCUtil.close(conn,ps);
        }

    }




}
